using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;
using System.ComponentModel.DataAnnotations;
using System.Text.Json;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("caipinxinxi")]
    public class DishController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly IFileService _fileService;

        public DishController(ApplicationDbContext context, IFileService fileService)
        {
            _context = context;
            _fileService = fileService;
        }

        /// <summary>
        /// 获取所有菜品
        /// </summary>
        [HttpGet("list")]
        public async Task<ActionResult<IEnumerable<DishDto>>> GetDishes()
        {
            var dishes = await _context.Dishes.ToListAsync();
            var categories = await _context.Categories.ToListAsync();

            var dishDtos = dishes.Select(d => 
            {
                var category = categories.FirstOrDefault(c => c.caipinfenlei == d.caipinfenlei);
                return new DishDto
                {
                    Id = d.id,
                    Name = d.caipinmingcheng,
                    Description = d.caipinjieshao,
                    Price = d.caipinjiage,
                    Image = d.tupian,
                    CategoryId = category?.id ?? 0,
                    CategoryName = category?.caipinfenlei ?? d.caipinfenlei,
                    IsAvailable = d.shangjia == "是",
                    ClickNum = d.clicknum,
                    AddTime = d.addtime
                };
            }).ToList();

            return Ok(new { code = 0, data = dishDtos });
        }

        /// <summary>
        /// 根据分类获取菜品
        /// </summary>
        [HttpGet("category/{categoryName}")]
        public async Task<ActionResult<IEnumerable<DishDto>>> GetDishesByCategory(string categoryName)
        {
            var dishes = await _context.Dishes
                .Where(d => d.caipinfenlei == categoryName)
                .ToListAsync();

            var category = await _context.Categories
                .FirstOrDefaultAsync(c => c.caipinfenlei == categoryName);

            var dishDtos = dishes.Select(d => new DishDto
            {
                Id = d.id,
                Name = d.caipinmingcheng,
                Description = d.caipinjieshao,
                Price = d.caipinjiage,
                Image = d.tupian,
                CategoryId = category?.id ?? 0,
                CategoryName = category?.caipinfenlei ?? d.caipinfenlei,
                IsAvailable = d.shangjia == "是",
                ClickNum = d.clicknum,
                AddTime = d.addtime
            }).ToList();

            return Ok(new { code = 0, data = dishDtos });
        }

        /// <summary>
        /// 获取菜品详情
        /// </summary>
        [HttpGet("detail/{id}")]
        public async Task<ActionResult<DishDto>> GetDish(long id)
        {
            var dish = await _context.Dishes
                .FirstOrDefaultAsync(d => d.id == id);

            if (dish == null)
            {
                return NotFound(new { code = 1, msg = "菜品不存在" });
            }

            // 查找分类
            var category = await _context.Categories
                .FirstOrDefaultAsync(c => c.caipinfenlei == dish.caipinfenlei);

            var dishDto = new DishDto
            {
                Id = dish.id,
                Name = dish.caipinmingcheng,
                Description = dish.caipinjieshao,
                Price = dish.caipinjiage,
                Image = dish.tupian,
                CategoryId = category?.id ?? 0,
                CategoryName = category?.caipinfenlei ?? dish.caipinfenlei,
                IsAvailable = dish.shangjia == "是",
                ClickNum = dish.clicknum,
                AddTime = dish.addtime
            };

            return Ok(new { code = 0, data = dishDto });
        }

        /// <summary>
        /// 获取菜品详情 - 兼容前端info接口
        /// </summary>
        [HttpGet("info/{id}")]
        public async Task<ActionResult<DishDto>> GetDishInfo(long id)
        {
            try
            {
                Console.WriteLine($"获取菜品详情，ID: {id}");
                var dish = await _context.Dishes
                    .FirstOrDefaultAsync(d => d.id == id);

                if (dish == null)
                {
                    Console.WriteLine($"菜品不存在，ID: {id}");
                    return NotFound(new { code = 1, msg = "菜品不存在" });
                }

                // 查找分类
                var category = await _context.Categories
                    .FirstOrDefaultAsync(c => c.caipinfenlei == dish.caipinfenlei);

                // 增加点击次数
                dish.clicknum += 1;
                await _context.SaveChangesAsync();

                // 返回前端期望的数据格式
                return Ok(new { 
                    code = 0, 
                    msg = "获取成功",
                    data = new {
                        id = dish.id,
                        caipinmingcheng = dish.caipinmingcheng,
                        caipinjieshao = dish.caipinjieshao,
                        caipinjiage = dish.caipinjiage,
                        tupian = dish.tupian,
                        caipinfenlei = dish.caipinfenlei,
                        shangjia = dish.shangjia,
                        clicknum = dish.clicknum,
                        cailiao = dish.cailiao,
                        fenliang = dish.fenliang,
                        addtime = dish.addtime
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取菜品详情失败: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return StatusCode(500, new { code = 1, msg = $"获取菜品详情失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 添加菜品
        /// </summary>
        [Authorize(Roles = "Admin")]
        [HttpPost("add")]
        public async Task<IActionResult> CreateDish([FromForm] CreateDishModel model)
        {
            var dish = new Dish
            {
                caipinmingcheng = model.Name,
                caipinjieshao = model.Description,
                caipinjiage = (int)model.Price,
                caipinfenlei = model.CategoryName,
                clicknum = 0,
                addtime = DateTime.Now
            };

            if (model.Image != null)
            {
                var imagePath = await _fileService.UploadFileAsync(model.Image, "dishes");
                if (string.IsNullOrEmpty(imagePath))
                {
                    return BadRequest("Failed to save image");
                }
                dish.tupian = imagePath;
            }

            _context.Dishes.Add(dish);
            await _context.SaveChangesAsync();

            return Ok(new { code = 0, msg = "添加成功" });
        }

        /// <summary>
        /// 更新菜品
        /// </summary>
        [Authorize(Roles = "Admin")]
        [HttpPost("update")]
        public async Task<IActionResult> UpdateDish([FromForm] UpdateDishModel model)
        {
            var dish = await _context.Dishes.FindAsync(model.id);
            if (dish == null)
            {
                return NotFound();
            }

            if (model.Image != null)
            {
                // 删除旧图片
                if (!string.IsNullOrEmpty(dish.tupian))
                {
                    await _fileService.DeleteFileAsync(dish.tupian);
                }

                // 保存新图片
                var imagePath = await _fileService.UploadFileAsync(model.Image, "dishes");
                if (string.IsNullOrEmpty(imagePath))
                {
                    return BadRequest("Failed to save image");
                }
                dish.tupian = imagePath;
            }

            dish.caipinmingcheng = model.Name;
            dish.caipinjieshao = model.Description;
            dish.caipinjiage = (int)model.Price;
            dish.caipinfenlei = model.CategoryName;
            dish.addtime = DateTime.Now;

            await _context.SaveChangesAsync();

            return Ok(new { code = 0, msg = "修改成功" });
        }

        /// <summary>
        /// 删除菜品
        /// </summary>
        [HttpDelete("delete")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> DeleteDish([FromQuery] long id)
        {
            var dish = await _context.Dishes.FindAsync(id);
            if (dish == null)
            {
                return NotFound();
            }

            // 删除图片
            if (!string.IsNullOrEmpty(dish.tupian))
            {
                await _fileService.DeleteFileAsync(dish.tupian);
            }

            _context.Dishes.Remove(dish);
            await _context.SaveChangesAsync();

            return Ok(new { code = 0, msg = "删除成功" });
        }

        /// <summary>
        /// 更新菜品状态
        /// </summary>
        [HttpPut("status/{id}")]
        [Authorize(Roles = "admin")]
        public async Task<IActionResult> UpdateDishStatus(long id, [FromBody] UpdateDishStatusModel model)
        {
            var dish = await _context.Dishes.FindAsync(id);
            if (dish == null)
            {
                return NotFound();
            }

            dish.shangjia = model.IsAvailable ? "是" : "否";
            dish.addtime = DateTime.Now;

            await _context.SaveChangesAsync();

            return Ok(new { code = 0, msg = "状态修改成功" });
        }

        /// <summary>
        /// 分页获取菜品
        /// </summary>
        [HttpGet("page")]
        public async Task<IActionResult> GetDishesPage(
            [FromQuery] int page = 1, 
            [FromQuery] int limit = 10,
            [FromQuery] string sort = "addtime",
            [FromQuery] string order = "desc")
        {
            var query = _context.Dishes.AsQueryable();

            // 排序
            if (sort == "addtime")
            {
                query = order == "desc" 
                    ? query.OrderByDescending(d => d.addtime)
                    : query.OrderBy(d => d.addtime);
            }
            else if (sort == "price")
            {
                query = order == "desc" 
                    ? query.OrderByDescending(d => d.caipinjiage)
                    : query.OrderBy(d => d.caipinjiage);
            }
            else if (sort == "clicknum")
            {
                query = order == "desc" 
                    ? query.OrderByDescending(d => d.clicknum)
                    : query.OrderBy(d => d.clicknum);
            }

            var totalCount = await query.CountAsync();
            var dishes = await query
                .Skip((page - 1) * limit)
                .Take(limit)
                .ToListAsync();

            // 获取所有分类
            var categories = await _context.Categories.ToListAsync();

            var dishList = dishes.Select(d => 
            {
                var category = categories.FirstOrDefault(c => c.caipinfenlei == d.caipinfenlei);
                // 确保图片URL不为空，并且不需要分割
                string imageUrl = !string.IsNullOrEmpty(d.tupian) ? d.tupian : "";
                
                // 如果图片URL不包含完整的URL前缀，添加前缀
                if (!string.IsNullOrEmpty(imageUrl) && !imageUrl.StartsWith("http"))
                {
                    // 使用当前请求的主机名构建完整URL
                    imageUrl = $"http://localhost:8080/ssmjxtr8/{imageUrl}";
                }
                
                return new
                {
                    id = d.id,
                    caipinmingcheng = d.caipinmingcheng,
                    caipinjieshao = d.caipinjieshao,
                    caipinjiage = d.caipinjiage,
                    tupian = imageUrl, // 使用处理后的图片URL
                    caipinfenlei = d.caipinfenlei,
                    categoryId = category?.id ?? 0,
                    categoryName = category?.caipinfenlei ?? d.caipinfenlei,
                    shangjia = d.shangjia == "是" ? "是" : "否", // 确保shangjia字段值为"是"或"否"
                    clicknum = d.clicknum,
                    addtime = d.addtime
                };
            }).ToList();

            return Ok(new
            {
                code = 0,
                data = new
                {
                    total = totalCount,
                    pageSize = limit,
                    totalPage = (int)Math.Ceiling(totalCount / (double)limit),
                    currPage = page,
                    list = dishList
                }
            });
        }
    }

    public class DishDto
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public string Image { get; set; }
        public long CategoryId { get; set; }
        public string CategoryName { get; set; }
        public bool IsAvailable { get; set; }
        public int ClickNum { get; set; }
        public DateTime AddTime { get; set; }
    }

    public class CreateDishModel
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public IFormFile Image { get; set; }
        public string CategoryName { get; set; }
        public bool IsAvailable { get; set; }
    }

    public class UpdateDishModel
    {
        public long id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public IFormFile Image { get; set; }
        public string CategoryName { get; set; }
        public bool IsAvailable { get; set; }
    }

    public class UpdateDishStatusModel
    {
        public bool IsAvailable { get; set; }
    }
} 